package com.cjh.service.impl;

import com.cjh.constant.JwtConstant;
import com.cjh.dto.LoginDto;
import com.cjh.entity.LoginUser;
import com.cjh.entity.User;
import com.cjh.exception.ResultException;
import com.cjh.service.LoginService;
import com.cjh.utils.JwtUtils;
import com.cjh.utils.RedisUtil;
import com.cjh.utils.ResultJson;
import com.cjh.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public ResultJson<LoginVo> login(LoginDto loginDto) {

        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginDto.getUserName(),loginDto.getPassWord());
        //AuthenticationManager authenticate进行用户认证
        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        //如果认证通过,使用userid生成jwt jwt存入响应体返回
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取User对象
        User user = loginUser.getUser();
        String userId = user.getId().toString();
        //生成token
        String token = JwtUtils.createToken(userId);
        LoginVo loginVo=new LoginVo();
        loginVo.setUserName(user.getUserName()).setToken(token);
        //把完整的用户信息存入redis
        redisUtil.set(JwtConstant.JWT_PREFIX+userId,loginUser,JwtConstant.EXPIRE_TIME);
        return ResultJson.ok(200,"ok",loginVo);
    }

    @Override
    public ResultJson logout() {

        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //删除redis中的token
        redisUtil.del(JwtConstant.JWT_PREFIX+loginUser.getUser().getId());
        return ResultJson.ok(200,"ok");
    }
}
